package com.rocky.study.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo1 {
    private static Semaphore semaphore=new Semaphore(1);

    public static void main(String[] args) {
        Runnable run=()->{
            boolean isAcquired=false;
            try {
                semaphore.acquire();//state-1
                Thread.currentThread().interrupt();
                semaphore.acquire();
                isAcquired=true;
                System.out.println(Thread.currentThread().getName()+"获取令牌。。。");
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(isAcquired) {
                    System.out.println(Thread.currentThread().getName() + "释放令牌。。。");
                    semaphore.release();//state+1
                }
                System.out.println(Thread.currentThread().getName() +"剩余令牌======"+semaphore.availablePermits());
            }
        };

        Thread t1=new Thread(run,"t1");
        t1.start();

        Thread t2=new Thread(run,"t2");
        t2.start();

        Thread t3=new Thread(run,"t3");
        t3.start();

        t2.interrupt();
        t3.interrupt();
    }
}
